<!--优惠券管理  -->
<template>
  <div class="box_container">
    <!-- 输入框 -->
    <div class="box_input">
      <el-input v-model="pageinfo.title" placeholder="请输入优惠券名称"></el-input>
      <el-select v-model="pageinfo.type" placeholder="请选择优惠券类型">
        <el-option v-for="item in couponTypeMap" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
      <el-select v-model="pageinfo.status" placeholder="请选择优惠券状态">
        <el-option v-for="item in couponStatusMap" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
      <el-button icon="el-icon-search" type="primary" @click="onSeek">查找</el-button>
      <el-button icon="el-icon-plus" type="primary" @click="addAdmin">添加</el-button>
      <el-button icon="el-icon-download" type="primary" @click="exportExcel">导出</el-button>
    </div>
    <!-- 优惠券管理列表 -->
    <div class="box_table" id="outTable">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="优惠券ID" align="center">
        </el-table-column>
        <el-table-column prop="title" label="优惠券名称" align="center">
        </el-table-column>
        <el-table-column prop="type" label="优惠券类型" align="center">
          <template slot-scope="scope">
            {{scope.row.type == 1? "满减券": "立减券"}}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="介绍" align="center">
        </el-table-column>
        <el-table-column prop="total" label="优惠券数量" align="center">
        </el-table-column>
        <el-table-column prop="surplus" label="剩余数量" align="center">
        </el-table-column>
        <el-table-column prop="limit" label="每人限额" align="center">
        </el-table-column>
        <el-table-column prop="discount" label="满减金额" align="center">
          <template slot-scope="scope">
            {{`减免${scope.row.discount}元`}}
          </template>
        </el-table-column>
        <el-table-column prop="min" label="最低消费" align="center">
          <template slot-scope="scope">
            {{`满${scope.row.min}元可用`}}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.gmtEnd<new Date()?'danger':scope.row.status?'primary':'warning'">
              <span v-text="scope.row.gmtEnd < new Date()?'已过期':scope.row.status? '正常': '下架'"></span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryTitle" label="使用类目名称" align="center">
          <template slot-scope="scope">
            <el-tag> {{scope.row.categoryTitle||"全部类目"}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryId" label="使用类目ID" align="center">
        </el-table-column>
        <el-table-column prop="days" label="领券相对天数" align="center">
          <template slot-scope="scope">
            {{scope.row.days??'无'}}
          </template>
        </el-table-column>
        <el-table-column prop="gmtStart" label="领券开始时间" align="center">
          <template slot-scope="scope">
            {{scope.row.gmtStart?new Date(scope.row.gmtStart).couponTime():'无'}}
          </template>
        </el-table-column>
        <el-table-column prop="gmtEnd" label="领券结束时间" align="center">
          <template slot-scope="scope">
            {{scope.row.gmtEnd?new Date(scope.row.gmtEnd).couponTime():'无'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" v-if="scope.row.gmtEnd<new Date()" @click="editStatus(scope.row)">已过期
            </el-button>
            <el-button size="mini" type="primary" v-else-if="scope.row.status==0" @click="editStatus(scope.row)">激活
            </el-button>
            <el-button size="mini" type="primary" v-else @click="editStatus(scope.row)">冻结</el-button>
            <el-button size="mini" type="info" @click="handCheck(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加--查看弹框 -->
    <el-dialog :title="title" :visible.sync="dialogTableVisible">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :disabled='title=="添加"?false:true'>
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择">
            <el-option v-for="item in couponTypeMap" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" prop="description">
          <el-input v-model="ruleForm.description" placeholder="请输入介绍信息"></el-input>
        </el-form-item>
        <el-form-item label="优惠券数量" prop="total">
          <el-input placeholder="请输入优惠券数量" v-model="ruleForm.total" @keyup.native="number">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限额" prop="limit">
          <el-input placeholder="请输入每人限额" v-model="ruleForm.limit" @keyup.native="number">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discount">
          <el-input placeholder="请输入优惠券金额" v-model="ruleForm.discount">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="min">
          <el-input placeholder="请输入最低消费" v-model="ruleForm.min">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券状态" prop="status">
          <el-select v-model="ruleForm.status" placeholder="请选择">
            <el-option v-for="item in couponStatusMap" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期">
          <template>
            <el-radio-group v-model="tabValue" style="margin-bottom: 30px;">
              <el-radio-button label="领券相对天数"></el-radio-button>
              <el-radio-button label="指定绝对时间"></el-radio-button>
            </el-radio-group>
            <div v-if="tabValue=='领券相对天数'">
              <el-input placeholder="请输入天数" v-model="ruleForm.days">
                <template slot="append">天</template>
              </el-input>
            </div>
            <div v-if="tabValue=='指定绝对时间'">
              <el-date-picker v-model="ruleForm.gmtStart" type="datetime" placeholder="选择日期时间">
              </el-date-picker>
              至
              <el-date-picker v-model="ruleForm.gmtEnd" type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <template>
            <el-radio-group v-model="tabValues">
              <el-radio-button label="全场通用"></el-radio-button>
              <el-radio-button label="指定分类"></el-radio-button>
            </el-radio-group>
          </template>
        </el-form-item>
        <div v-if="tabValues=='指定分类'">
          <el-form-item label="优惠类目">
            <el-cascader v-model="ruleForm.categoryId" :options="options" :props="defaultParams" clearable placeholder="请选择优惠类目"></el-cascader>
          </el-form-item>
        </div>
        <el-form-item style="display: flex;justify-content: end;">
          <el-button @click="resetForm('ruleForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分页 --回到顶部 -->
    <div class="box_paging">
      <pagination :pageinfo="pageinfo" @change="changePage"></pagination>
    </div>
  </div>
</template>
<script>
import Pagination from "../../components/pagination/MyPagination.vue" //分页组件
import Apiadmin from "../../api/admin"
import { debounce } from '../../utils/debounce' //防抖
// 导出excel
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      pageinfo: {
        limit: 10, //每页显示的数量
        page: 1, //当前显示的页码
        total: 0, //数据总条数
        title: '', //优惠券名称
        type: '', //优惠券类型
        status: '', //优惠券状态
      },
      tableData: [], //表格数据

      // 下拉框数据
      //优惠券类型
      couponTypeMap: [{
        value: 1,
        name: '满减卷'
      }, {
        value: 2,
        name: '立减券'
      }, {
        value: null,
        name: '全部'
      },],
      value: '',
      //优惠券状态
      couponStatusMap: [{
        value: 0,
        name: '下架'
      }, {
        value: 1,
        name: '正常'
      }, {
        value: -1,
        name: '已过期'
      },
      {
        value: null,
        name: '全部'
      },
      ],
      // 表单数据
      ruleForm: {
        title: '', //优惠券名称
        type: '', //优惠券类型
        description: '', //介绍
        total: '', //优惠券数量
        limit: '', //每人限额
        discount: '', //优惠金额
        min: '', //最低消费
        status: '', //优惠券状态
        days: '', //有效期--领券天数
        gmtStart: '', //有效期--领券开始时间
        gmtEnd: '', //有效期--领券结束时间
        categoryId: '', //商品限制范围
      },
      tabValue: '领券相对天数',
      tabValues: '全场通用',
      // 表单验证
      rules: {
        title: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择优惠券类型', trigger: 'blur' }],
        total: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { pattern: /^[0-9]+?[0-9]*/, message: '格式不正确、请输入数字' },
        ],
        limit: [
          { required: true, message: '请输入限额', trigger: 'blur' },
          { pattern: /^[0-9]+?[0-9]*/, message: '格式不正确、请输入数字' },
        ],
        discount: [
          { required: true, message: '请输入优惠金额', trigger: 'blur' },
          { pattern: /^[0-9]+?[0-9]*/, message: '格式不正确、请输入数字' },
        ],
        min: [
          { required: true, message: '请输入最低消费', trigger: 'blur' },
          { pattern: /^[0-9]+?[0-9]*/, message: '格式不正确、请输入数字' },
        ],
        status: [{ required: true, message: '请选择优惠券状态', trigger: 'blur' }],
        days: [{ pattern: /^[0-9]+?[0-9]*/, message: '格式不正确、请输入数字' }]
      },
      dialogTableVisible: false, //编辑弹框隐藏
      options: [], //优惠类目数据
      defaultParams: { // 级联选择器的配置
        checkStrictly: true, // 父子节点不互相关联
        label: 'title',  //渲染上去的名字
        value: 'id', //选中时的id
        children: 'childrenList',  //子节点数组
        emitPath: false // 只返回该节点的值
      },
      title: '',//弹框添加或查看
    }
  },
  created() {
    this.operateList()
  },
  methods: {
    //验证优惠券数量和限额多少张只能是整数
    number() {
      this.ruleForm.total = this.ruleForm.total.replace(/[^\.\d]/g, '');
      this.ruleForm.total = this.ruleForm.total.replace('.', '');
      this.ruleForm.limit = this.ruleForm.limit.replace(/[^\.\d]/g, '');
      this.ruleForm.limit = this.ruleForm.limit.replace('.', '');
    },
    // 请求优惠券用户数据
    operateList() {
      Apiadmin.couponList({
        ...this.pageinfo,
        pageNo: this.pageinfo.page
      }).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.tableData = res.data.items //表格数据
          this.pageinfo.total = res.data.count //分页总数据
        }
      })
      // 请求优惠类目数据
      Apiadmin.categoryTree({}).then(res => {
        // console.log(res)
        this.options = res.data
      })
    },
    //查找优惠券用户
    onSeek() {
      this.pageinfo.page = 1, //查找页数重置为1
        // 请求数据时加载
        this.$showLoading(() => {
          this.operateList()
        })
    },
    // 激活冻结
    editStatus: debounce(function (row) { //防抖操作.避免连续点击
      // console.log(row)
      if (row.gmtEnd < new Date()) {
        this.$message({
          message: '已过期,建议删除!',
          type: 'error'
        });
        return
      }
      let status = row.status ? 0 : 1;
      Apiadmin.couponStatus({
        id: row.id,
        status
      }).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.$message({
            message: status == 0 ? '冻结成功' : '激活成功',
            type: status == 0 ? 'error' : 'success'
          });
          this.operateList() //刷新页面
        }
      })
    }, 1000),
    //添加优惠券用户
    addAdmin() {
      this.dialogTableVisible = true
      this.title = "添加"
      this.tabValue = "领券相对天数"
      this.tabValues = "全场通用"
      this.ruleForm = {  //清空
        title: '', //优惠券名称
        type: '', //优惠券类型
        description: '', //介绍
        total: '', //优惠券数量
        limit: '', //每人限额
        discount: '', //优惠金额
        min: '', //最低消费
        status: '', //优惠券状态
        days: '', //有效期--领券天数
        gmtStart: '', //有效期--领券开始时间
        gmtEnd: '', //有效期--领券结束时间
        categoryId: '', //商品限制范围
      }
    },
    // 查看优惠券用户
    handCheck(row) {
      // console.log(row);
      this.dialogTableVisible = true
      this.title = "查看"
      // 查看是已过期显示过期状态
      if (row.gmtEnd < new Date().getTime()) {
        row.status = "已过期"
      }
      this.ruleForm = row
      // console.log({ ...row })
      // 判断指定绝对时间有值时显示指定时间按钮
      if (row.gmtStart && row.gmtEnd) {
        this.tabValue = "指定绝对时间"
      } else {
        this.tabValue = "领券相对天数"
      }
      if (row.categoryId) {
        this.tabValues = "指定分类"
      } else {
        this.tabValues = "全场通用"
      }

    },
    //添加提交按钮
    submitForm(formName) {
      // console.log({ ...this.ruleForm })
      // return
      // 优惠券数量要高于每人限额
      if (this.ruleForm.total < this.ruleForm.limit) {
        this.$message({
          message: "优惠券数量要高于每人限额",
          type: 'error'
        });
        return
      }
      // 最低消费min 要高于 满减券discount
      if (this.ruleForm.min < this.ruleForm.discount) {
        this.$message({
          message: "最低消费要高于满减券",
          type: 'error'
        });
        return
      }
      // 领券开始时间要低于领券结束时间
      if (this.ruleForm.gmtStart > this.ruleForm.gmtEnd) {
        this.$message({
          message: "领券开始时间要低于领券结束时间",
          type: 'error'
        });
        return
      }
      //判断指定绝对时间有值转换成时间戳
      if (this.ruleForm.gmtStart && this.ruleForm.gmtEnd) {
        this.ruleForm.gmtStart = new Date(this.ruleForm.gmtStart).getTime()
        this.ruleForm.gmtEnd = new Date(this.ruleForm.gmtEnd).getTime()
      }
      // console.log(new Date(this.ruleForm.gmtEnd).getTime())
      // return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title == '添加') {
            Apiadmin.couponAdd(this.ruleForm).then(res => {
              // console.log(res)
              if (res.errno == 200) {
                this.dialogTableVisible = false
                this.operateList() //刷新页面
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: "该用户已存在",
                  type: 'error'
                });
              }
            }).catch(err => {
              console.log(err)
            })
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //取消按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogTableVisible = false  //弹框关闭
    },
    // 导出
    exportExcel() {
      var xlsxParam = {
        raw: true
      }; //转换成excel时，使用原始的格式
      var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"), xlsxParam); //outTable为列表id
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: "application/octet-stream;charset=utf-8"
          }),
          "优惠券列表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    // 子传过来的方法和页长跟当前页
    changePage(e) {
      // console.log(e)
      this.pageinfo = JSON.parse(JSON.stringify(e))
      this.$nextTick(() => {
        this.operateList()
      })
    },

  }
}
</script>
<style scoped lang="less">
.box_input {
  .el-input {
    width: 15%;
  }
}
</style>